package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {
	public static boolean downloadFile(String httpFile, String saveFile) {
		if (httpFile == null || saveFile == null)
			return false;
		URL url = null;
		try {
			url = new URL(httpFile);
		} catch (MalformedURLException urlex) {
			urlex.printStackTrace();
			return false;
		}
		if (!checkDirectory(saveFile)){
			return false;
		}

		deleteFile(saveFile);
		DataInputStream in = null;
		DataOutputStream out = null;
		try {
			in = new DataInputStream(new BufferedInputStream(url.openStream()));
			if(in == null) return false;
			out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(saveFile)));
			byte[] buf = new byte[1024];
			int readed = 0;
			while ((readed = in.read(buf)) != -1) {
				out.write(buf, 0, readed);
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			return false;
		}finally{
			try {
				if(in != null) in.close();
				if(out != null) out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public static boolean checkDirectory(String tragetFile) {
		File targetFile = new File(tragetFile);
		File directory = new File(targetFile.getParent());
		if (!directory.exists() && !directory.mkdirs()) {
			return false;
		}
		return true;
	}

	public static void deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
	}
	
}
